<template>
  <a-card :bordered="false">
    <template #title>
      <a-space size="small">
        <LeftCircleTwoTone style="font-size: 20px" @click="$emit('showTable', props.group)"></LeftCircleTwoTone>
        {{ props.recode.id ? '编辑 ： ' + props.recode.chartTitle + '【' + props.recode.id + '】' : '添加' }}
      </a-space>
    </template>

    <a-form :model="formState" name="basic" :label-col="{ span: 3 }" autocomplete="off" @finish="onFinish">
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="分组"
            name="bizGroupValue"
            :label-col="{ span: 9 }"
            :rules="[{ required: true, message: '请输入分组!' }]"
          >
            <a-select
              v-model:value="formState.bizGroupValue"
              style="width: 200px"
              placeholder="请选择分组"
              :options="groupOptions"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="标题"
            name="chartTitle"
            :label-col="{ span: 6 }"
            :rules="[{ required: true, message: '请输入标题!' }]"
          >
            <a-input v-model:value="formState.chartTitle" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item name="chartConfig" :rules="[{ required: true, message: '请输入数据设置!' }]">
        <template #label>
          数据设置&nbsp;
          <a-popover title="字段说明：具体设置请参照DEMO分组下的设置！" placement="rightTop">
            <template #content>
              <div>cron：数据收集时间，请严格遵循cron的标准，尽量不要大量任务都用同一个cron表达式，避免排队！</div>
              <div>serialId：图序列的serialId，请保证在本设置中唯一！</div>
              <div>serialName：图序列的名称</div>
              <div>
                executorType：数据收集器类型
                <a-typography-paragraph :copyable="{ text: 'i5xRdb' }">
                  &nbsp;&nbsp;&nbsp;&nbsp;内嵌的智慧餐厅关系型数据库：i5xRdb
                </a-typography-paragraph>
                <a-typography-paragraph :copyable="{ text: 'i5xMongo' }">
                  &nbsp;&nbsp;&nbsp;&nbsp;内嵌的智慧餐厅Mongo数据库：i5xMongo
                </a-typography-paragraph>
                <a-typography-paragraph :copyable="{ text: 'rdb' }">
                  &nbsp;&nbsp;&nbsp;&nbsp;关系型数据库：rdb
                </a-typography-paragraph>
                <a-typography-paragraph :copyable="{ text: 'mongo' }">
                  &nbsp;&nbsp;&nbsp;&nbsp;文档数据库mongo：mongo
                </a-typography-paragraph>
                <a-typography-paragraph :copyable="{ text: 'http' }">
                  &nbsp;&nbsp;&nbsp;&nbsp;restful请求：http
                </a-typography-paragraph>
              </div>
            </template>
            <ExclamationCircleTwoTone />
          </a-popover>
        </template>
        <VAceEditor
          v-model:value="formState.chartConfig"
          lang="json"
          theme="dracula"
          :options="{ useWorker: true, tabSize: 2 }"
          :min-lines="40"
          :max-lines="40"
          :wrap="true"
          @change="checkJson"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-space size="middle">
          <a-button type="primary" html-type="submit" :disabled="submitDisable">
            {{ props.recode.id ? '更新' : '添加' }}
          </a-button>
          <a-button type="primary" @click="$emit('showTable', props.group)">返回</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { ExclamationCircleTwoTone, LeftCircleTwoTone } from '@ant-design/icons-vue';
import { message, type SelectProps } from 'ant-design-vue';
import { VAceEditor } from 'vue3-ace-editor';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-dracula';
import ace from 'ace-builds';
import workerJsonUrl from 'ace-builds/src-noconflict/worker-json?url';
import type { Chart } from '@/api/bizDashboard/bizDashboard';
import * as bizDashboardApi from '@/api/bizDashboard/bizDashboard';
import { Base64 } from 'js-base64';

ace.config.setModuleUrl('ace/mode/json_worker', workerJsonUrl);

const props = defineProps<{
  recode: Chart;
  group: number;
  groupOptions: SelectProps['options'];
}>();

const emit = defineEmits<{
  (e: 'showTable', group: number): void;
}>();

//chart
const formState: Chart = reactive(props.recode);
const defaultChartConfig: any = {
  chartType: 'job',
  cron: '16 16 23 * * ?',
  series: [
    {
      serialId: 'wechatCount',
      serialName: '授权的微信公众号总数',
      executorType: 'i5xRdb',
      fromDataSource: 'platform-ds-slave',
      fromQuerySql: 'select count(*) from wxapiaddr w where w.isopenrefresh = 1  and w.cappid is not null',
    },
  ],
};

formState.chartConfig = formState.chartConfig ? formState.chartConfig : JSON.stringify(defaultChartConfig, null, 2);

//提交button
let submitDisable = ref(false);

function checkJson() {
  try {
    JSON.parse(formState.chartConfig);
    submitDisable.value = false;
  } catch (err) {
    console.log(err);
    submitDisable.value = true;
  }
}

function onFinish() {
  console.log('Success:', formState);
  submitDisable.value = true;
  //加密
  let base64FormState = Base64.encode(JSON.stringify(formState));
  console.log('加密后Success:', base64FormState);
  bizDashboardApi.saveChart(base64FormState).then(jsonResult => {
    submitDisable.value = false;
    if (!jsonResult) {
      return;
    }
    emit('showTable', props.group);
    message.success(formState.id ? '更新成功！' : '添加成功');
  });
}
</script>

<style lang="less" scoped></style>
